package com.library.service;

import com.library.dao.*;
import com.library.dao.BorrowRepository;
import com.library.entity.Book;
import com.library.entity.BorrowRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BorrowService {
    @Autowired
    private BookRepository bookRepository;
    @Autowired
    private BorrowRepository borrowRepository;

    /**
     * 将书籍添加到借阅车。
     *
     * @param bookId 书籍ID。
     * @param cart 书籍数组
     * @return 操作结果的消息。
     */
    public List<Book> addToCart(Long bookId,List<Book> cart ) {
        // 根据书籍ID获取书籍
        Book book = bookRepository.findById(bookId);
        cart.add(book);
        // 判断书籍的可用副本数量
        return cart;
    }

    public List<Book> deleteFromCart(Long bookId, List<Book> cart) {
        cart.removeIf(book -> book.getId().equals(bookId));
        return cart;
    }

    public Boolean submitBorrowRequest(List<Book> cart,long userID,List<Integer> days) {
        if (cart == null) {
            return false;
        }
        List<BorrowRequest> borrowRequests = new ArrayList<>();
        int index=0;
        for (Book book : cart) {
            Date date = new Date();
            long millisecondsInDay = 24 * 60 * 60 * 1000L; // 一天的毫秒数
            long newTime = date.getTime() + (days.get(index) * millisecondsInDay);
            BorrowRequest borrowRequest = new BorrowRequest(null,(long)userID,book.getId(),null, date,null, new Date(newTime),null);
            borrowRequests.add(borrowRequest);
            index++;
        }
        borrowRepository.addBorrowRequest(borrowRequests);
        //被解约的书籍-1
        return true;
    }

    /**
     *
     * @return 从数据库查找并返回所有的借阅请求
     */
    public List<BorrowRequest> findAllBR(long userId) {
        return borrowRepository.findAll(userId);
    }
    //同意
    public void agreeBorrowRequest(long id) {
        borrowRepository.agreeBorrowRequest(id,new Date());
    }
    //拒绝
    public void rejectBorrowRequest(long id) {
        borrowRepository.rejectBorrowRequest(id);
    }
    //归还
    public void returnBorrowRequest(long id) {
        borrowRepository.returnBorrowRequest(id,new Date());
    }
    //删除
    public void deleteBorrowRequest(long id) {
        borrowRepository.deleteBorrowRequest(id);
    }
}
